<script setup>

import {onMounted, ref} from "vue";
import axios from "axios";
import * as echarts from "echarts";

const dataList = ref([]);

// 创建一个响应式引用来保存DOM元素
const chartDom = ref();

// 创建一个对象，保存Echarts实例
let chartInstance = null;

async function initData(){
  const apiRes = await axios.get('http://localhost:8080/NewEnergyChargeWeek');
  dataList.value = apiRes.data;
  initEcharts();
}

function initEcharts(){

  chartInstance = echarts.init(chartDom.value);
  const colors = ['#5470C6', '#91CC75', '#EE6666'];

  const option = {
    color: colors,
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    grid: {
      right: '20%'
    },
    toolbox: {
      feature: {
        dataView: { show: true, readOnly: false },
        restore: { show: true },
        saveAsImage: { show: true }
      }
    },
    legend: {
      data: ['充电总时间', '充电总费用', '充电总次数']
    },
    xAxis: [
      {
        type: 'category',
        axisTick: {
          alignWithLabel: true
        },
        data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat','Sun'],
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '充电总时间',
        position: 'right',
        alignTicks: true,
        axisLine: {
          show: true,
          lineStyle: {
            color: colors[0]
          }
        },
        axisLabel: {
          formatter: '{value} 小时'
        }
      },
      {
        type: 'value',
        name: '充电总费用',
        position: 'right',
        alignTicks: true,
        offset: 80,
        axisLine: {
          show: true,
          lineStyle: {
            color: colors[1]
          }
        },
        axisLabel: {
          formatter: '{value} 元'
        }
      },
      {
        type: 'value',
        name: '充电总次数',
        position: 'left',
        alignTicks: true,
        axisLine: {
          show: true,
          lineStyle: {
            color: colors[2]
          }
        },
        axisLabel: {
          formatter: '{value} 次'
        }
      }
    ],
    series: [
      {
        name: '充电时间（⼩时）',
        type: 'bar',
        data:  dataList.value.dataCnt[0]
      },
      {
        name: '充电总费用（元）',
        type: 'bar',
        yAxisIndex: 1,
        data: dataList.value.dataCnt[1]
      },
      {
        name: '充电总次数',
        type: 'line',
        yAxisIndex: 2,
        data: dataList.value.dataCnt[2]
      }
    ]
  };
  chartInstance.setOption(option);
}

onMounted(() => {
  initData();
})
</script>

<template>
  <div ref="chartDom" style="width: 800px;height: 500px"></div>
</template>

<style scoped>

</style>
